<template>
  <div class="room-products-component">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="15" animated />
      <div class="loading-tip">
        <el-alert
          title="正在查询房型及价格信息，请稍候..."
          type="info"
          :closable="false"
          show-icon
        >
          <div class="loading-description">
            响应可能需要较长时间，请耐心等待。
          </div>
        </el-alert>
      </div>
    </div>
    
    <template v-else>
      <el-card class="search-card">
        <template #header>
          <div class="card-header">
            <h2>查询条件</h2>
          </div>
        </template>
        
        <el-form :model="searchForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入住日期">
                <el-date-picker
                  v-model="searchForm.checkInDate"
                  type="date"
                  placeholder="选择入住日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="离店日期">
                <el-date-picker
                  v-model="searchForm.checkOutDate"
                  type="date"
                  placeholder="选择离店日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button type="primary" @click="fetchRoomProducts" :loading="loading">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card v-if="rooms.length > 0" class="rooms-card">
        <template #header>
          <div class="card-header">
            <h2>房型及价格列表</h2>
            <span>共 {{ filteredAndSortedRooms.length }} 条</span>
          </div>
        </template>
        
        <el-alert
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <template #title>
            <strong>重要提示：</strong>政策编码 (policyCode) 和 唯一ID (uniqueId) 每次查询都会变化，有效期 30 分钟，请在选择后立即使用。
          </template>
        </el-alert>
        
        <!-- 筛选和排序区域 -->
        <div class="filter-sort-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-select 
                v-model="filterGroup" 
                placeholder="选择房型分组" 
                clearable
                style="width: 100%;"
              >
                <el-option label="全部分组" value=""></el-option>
                <el-option 
                  v-for="group in availableGroups" 
                  :key="group" 
                  :label="group" 
                  :value="group"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select 
                v-model="sortField" 
                placeholder="选择排序字段" 
                style="width: 100%;"
              >
                <el-option label="不排序" value=""></el-option>
                <el-option label="销售价" value="amountPrice"></el-option>
                <el-option label="结算价" value="settAmount"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select 
                v-model="sortOrder" 
                placeholder="选择排序方式" 
                style="width: 100%;"
                :disabled="!sortField"
              >
                <el-option label="由低到高" value="asc"></el-option>
                <el-option label="由高到低" value="desc"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>
        
        <el-table :data="filteredAndSortedRooms" stripe class="room-table">
          <el-table-column type="expand">
            <template #default="props">
              <div class="room-expand-content">
                <el-descriptions :column="2" border size="small">
                  <el-descriptions-item label="房型编码">{{ props.row.roomCode }}</el-descriptions-item>
                  <el-descriptions-item label="政策编码">{{ props.row.policyCode }}</el-descriptions-item>
                  <el-descriptions-item label="分组ID">{{ props.row.groupId }}</el-descriptions-item>
                  <el-descriptions-item label="价格计划编码">{{ props.row.planCode }}</el-descriptions-item>
                  <el-descriptions-item label="床型">{{ props.row.bedType || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="房间面积">{{ props.row.roomArea || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="楼层">{{ props.row.floor || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="最大入住人数">{{ props.row.maxGuestNum || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="窗户类型">{{ getWindowTypeName(props.row.windowType) }}</el-descriptions-item>
                  <el-descriptions-item label="网络">{{ props.row.internet || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="加床费">¥{{ (props.row.extraBed || 0).toFixed(2) }}</el-descriptions-item>
                  <el-descriptions-item label="货币">{{ props.row.currency }}</el-descriptions-item>
                </el-descriptions>
                
                <div v-if="props.row.roomDesc" style="margin-top: 15px;">
                  <h4>房间描述</h4>
                  <p>{{ props.row.roomDesc }}</p>
                </div>
                
                <div v-if="props.row.roomFaclities && props.row.roomFaclities.length > 0" style="margin-top: 15px;">
                  <h4>房间设施</h4>
                  <div class="facilities-list">
                    <el-tag v-for="(facility, index) in props.row.roomFaclities" :key="index" size="small" type="success" style="margin: 5px;">
                      {{ facility }}
                    </el-tag>
                  </div>
                </div>
                
                <div v-if="props.row.images && props.row.images.length > 0" style="margin-top: 15px;">
                  <h4>房间图片</h4>
                  <div class="room-images">
                    <img v-for="(img, index) in props.row.images.slice(0, 5)" :key="index" :src="img" alt="房间图片" class="room-image-thumb">
                  </div>
                </div>
                
                <div v-if="props.row.dailyPrices && props.row.dailyPrices.length > 0" style="margin-top: 15px;">
                  <h4>每日价格明细</h4>
                  <el-table :data="props.row.dailyPrices" size="small" border>
                    <el-table-column prop="date" label="日期" width="120"></el-table-column>
                    <el-table-column label="销售价" width="120">
                      <template #default="scope">
                        <span class="price">¥{{ scope.row.salePrice.toFixed(2) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="结算价" width="120">
                      <template #default="scope">
                        ¥{{ scope.row.settPrice.toFixed(2) }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                
                <div v-if="props.row.policyRules && props.row.policyRules.length > 0" style="margin-top: 15px;">
                  <h4>政策规则</h4>
                  <el-alert 
                    v-for="(rule, index) in props.row.policyRules" 
                    :key="index"
                    :title="rule.policyType === 'REFUND' ? '退款政策' : rule.policyType"
                    :description="rule.desc"
                    :type="rule.policyType === 'REFUND' ? 'warning' : 'info'"
                    :closable="false"
                    style="margin-bottom: 10px;"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="房型名称" width="180">
            <template #default="scope">
              <div>
                <strong>{{ scope.row.roomName }}</strong>
                <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                  {{ scope.row.roomGroup || '-' }}
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="价格计划" width="150">
            <template #default="scope">
              {{ scope.row.planName }}
            </template>
          </el-table-column>
          
          <el-table-column label="房间状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.roomStatus === 'APPLY' ? 'success' : 'danger'" size="small">
                {{ scope.row.roomStatus === 'APPLY' ? '有房' : '满房' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="80">
            <template #default="scope">
              {{ scope.row.roomQuantity }} 间
            </template>
          </el-table-column>
          
          <el-table-column label="支付方式" width="100">
            <template #default="scope">
              <el-tag size="small" :type="scope.row.payType === 'P2' ? 'success' : 'info'">
                {{ scope.row.payType === 'P2' ? '预付' : scope.row.payType }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="早餐" width="120">
            <template #default="scope">
              <div>
                <div>{{ getBreakfastName(scope.row.breakfast) }}</div>
                <div v-if="scope.row.breakfastCount" style="font-size: 12px; color: #909399;">
                  {{ scope.row.breakfastCount }}份
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="餐食描述" width="120">
            <template #default="scope">
              {{ scope.row.mealDesc || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="总价" width="120">
            <template #default="scope">
              <div>
                <div class="price">¥{{ scope.row.amountPrice.toFixed(2) }}</div>
                <div style="font-size: 12px; color: #909399;">
                  结算价: ¥{{ scope.row.settAmount.toFixed(2) }}
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                :disabled="scope.row.roomStatus !== 'APPLY'"
                @click="selectRoom(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <el-empty v-else-if="hasSearched" description="暂无房型数据"></el-empty>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { getRoomProducts } from '../api/hotelApi';
import { ElMessage } from 'element-plus';

const props = defineProps({
  hotelId: {
    type: [String, Number],
    required: true
  },
  checkInDate: {
    type: String,
    default: ''
  },
  checkOutDate: {
    type: String,
    default: ''
  }
});

const loading = ref(false);
const rooms = ref([]);
const hasSearched = ref(false);

// 筛选和排序相关
const filterGroup = ref('');  // 分组筛选
const sortField = ref('');    // 排序字段：amountPrice 或 settAmount
const sortOrder = ref('asc'); // 排序方式：asc 或 desc

// 获取当前日期和明天日期
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const searchForm = reactive({
  checkInDate: props.checkInDate || formatDate(today),
  checkOutDate: props.checkOutDate || formatDate(tomorrow)
});

// 监听props变化
watch(() => [props.checkInDate, props.checkOutDate], ([newCheckIn, newCheckOut]) => {
  if (newCheckIn) searchForm.checkInDate = newCheckIn;
  if (newCheckOut) searchForm.checkOutDate = newCheckOut;
}, { immediate: true });

// 获取所有可用的分组
const availableGroups = computed(() => {
  const groups = new Set();
  rooms.value.forEach(room => {
    if (room.roomGroup) {
      groups.add(room.roomGroup);
    }
  });
  return Array.from(groups).sort();
});

// 筛选和排序后的房型列表
const filteredAndSortedRooms = computed(() => {
  let result = [...rooms.value];
  
  // 1. 分组筛选
  if (filterGroup.value) {
    result = result.filter(room => room.roomGroup === filterGroup.value);
  }
  
  // 2. 排序
  if (sortField.value) {
    result.sort((a, b) => {
      const aValue = a[sortField.value] || 0;
      const bValue = b[sortField.value] || 0;
      
      if (sortOrder.value === 'asc') {
        return aValue - bValue;  // 由低到高
      } else {
        return bValue - aValue;  // 由高到低
      }
    });
  }
  
  return result;
});

// 获取窗户类型名称
const getWindowTypeName = (type) => {
  const typeMap = {
    'HAVE': '有窗',
    'NONE': '无窗',
    'INSIDE': '内窗',
    'SOMEONE': '部分有'
  };
  return typeMap[type] || type || '-';
};

// 获取早餐名称
const getBreakfastName = (type) => {
  const breakfastMap = {
    'B1': '单早',
    'B2': '双早',
    'B3': '床位早',
    'B4': '无早餐',
    'B5': '有早餐'
  };
  return breakfastMap[type] || type || '-';
};

const fetchRoomProducts = async () => {
  if (!props.hotelId) {
    ElMessage.error('缺少酒店编码参数');
    return;
  }
  
  if (!searchForm.checkInDate || !searchForm.checkOutDate) {
    ElMessage.warning('请选择入住和离店日期');
    return;
  }
  
  loading.value = true;
  hasSearched.value = true;
  
  try {
    const params = {
      hotelCode: props.hotelId,
      checkInDate: searchForm.checkInDate,
      checkOutDate: searchForm.checkOutDate,
      adultCount: 1,
      childCount: 0
    };
    
    const response = await getRoomProducts(params);
    
    console.log('房型产品API响应:', response);
    
    if (response.data) {
      // 接口返回的data中包含rooms数组
      if (response.data.rooms && Array.isArray(response.data.rooms)) {
        rooms.value = response.data.rooms;
      } else {
        rooms.value = [];
      }
      
      if (rooms.value.length === 0) {
        ElMessage.info('未找到房型数据');
      } else {
        ElMessage.success(`找到 ${rooms.value.length} 条房型价格信息`);
      }
    } else {
      ElMessage.error(`查询失败: ${response.msg || response.message || '未知错误'}`);
      rooms.value = [];
    }
  } catch (error) {
    console.error('查询房型及产品出错:', error);
    ElMessage.error('查询房型及产品出错，请稍后重试');
    rooms.value = [];
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  searchForm.checkInDate = formatDate(today);
  searchForm.checkOutDate = formatDate(tomorrow);
  // 重置筛选和排序
  filterGroup.value = '';
  sortField.value = '';
  sortOrder.value = 'asc';
};

const selectRoom = (room) => {
  ElMessage.success({
    message: `已选择房型：${room.roomName}，价格计划：${room.planName}`,
    duration: 3000
  });
  console.log('选择的房型信息:', room);
  // 这里可以跳转到预订页面或者调用预订接口
};

// 监听hotelId变化，重新获取房型数据
watch(() => props.hotelId, (newVal) => {
  if (newVal) {
    fetchRoomProducts();
  }
}, { immediate: true });
</script>

<style scoped>
.room-products-component {
  width: 100%;
}

.loading-container {
  position: relative;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.loading-tip {
  margin-top: 20px;
}

.loading-description {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}

.search-card, .rooms-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.room-table {
  width: 100%;
}

.room-expand-content {
  padding: 20px;
  background-color: #f5f7fa;
}

.room-expand-content h4 {
  margin: 15px 0 10px 0;
  font-size: 14px;
  color: #606266;
}

.facilities-list {
  display: flex;
  flex-wrap: wrap;
}

.room-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.room-image-thumb {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.room-image-thumb:hover {
  transform: scale(1.1);
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

/* 筛选排序区域 */
.filter-sort-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
